package cn.acewill.yxd.yunxundian.ui.follow_up;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Main;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Row;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.pubClass.reportQuery;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.follow_up.adapter.FollowUpRowAdapter;
import cn.acewill.yxd.yunxundian.ui.follow_up.nodeStruct.FU_main;
import cn.acewill.yxd.yunxundian.ui.follow_up.nodeStruct.FU_row;

@ContentView(R.layout.activity_follow_up_row)
public class FollowUpRowActivity extends BaseActivity {
    protected DbManager db = x.getDb(new YXDAPP().getDaoConfig());
    public static final int STATUS_SM = 1;
    public static final int STATUS_OC = 2;
    public static final int STATUS_BOTH = 3;
    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    @ViewInject(R.id.textTitle)
    private TextView mTitle;
    @ViewInject(R.id.myRecycle)
    private RecyclerView mRecyclerView;
    @ViewInject(R.id.errorText)
    private TextView errorText;
    private FU_main node;
    private int status=0;
    private boolean shallWePass = true, isAllUL = true;
    private List<t_Feedback_Row> tfrList;
    private Menu activityMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        node = (FU_main) getIntent().getSerializableExtra("node");
        if(node.empId == MainActivity.id)
            status = STATUS_OC;
        mTitle.setText(node.schName);

        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null){
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_task_submit,menu);
        List<FU_row> fuRowList = initDataList();
        if(fuRowList.size()>0){
            if(node.states>0){
                menu.findItem(R.id.submitData).setVisible(false);
            }else if(status>STATUS_SM && shallWePass){
                menu.findItem(R.id.submitData).setTitle("确认通过");
            }else if((status==STATUS_SM && shallWePass)||(status==STATUS_OC && !shallWePass)){
                menu.findItem(R.id.submitData).setVisible(false);
            }
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            mRecyclerView.setAdapter(new FollowUpRowAdapter(this, fuRowList));
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        }else{
            errorText.setVisibility(View.VISIBLE);
            menu.findItem(R.id.submitData).setVisible(false);
        }
        activityMenu = menu;
        //Log.i("FollowUpRowActivity","onCreateOptionsMenu");
        return true;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //Log.i("FollowUpRowActivity", "onRestart");
        status = node.empId==MainActivity.id?STATUS_OC:0;
        shallWePass = true;
        isAllUL = true;
        List<FU_row> fuRowList = initDataList();
        if(fuRowList.size()>0){
            if(node.states>0){
                activityMenu.findItem(R.id.submitData).setVisible(false);
            }else if(status>STATUS_SM && shallWePass){
                activityMenu.findItem(R.id.submitData).setTitle("确认通过");
            }else if((status==STATUS_SM && shallWePass)||(status==STATUS_OC && !shallWePass)){
                activityMenu.findItem(R.id.submitData).setVisible(false);
            }
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            mRecyclerView.setAdapter(new FollowUpRowAdapter(this, fuRowList));
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        }else{
            errorText.setVisibility(View.VISIBLE);
            activityMenu.findItem(R.id.submitData).setVisible(false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.submitData:
                submitOrPass();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private List<FU_row> initDataList(){
        List<FU_row> fuRowList = new ArrayList<>();
        try {
            reportQuery rQuery = new reportQuery(node.schId);
            WhereBuilder wb = status==STATUS_OC
                    ?WhereBuilder.b("shopmanid","!=",0)
                    :WhereBuilder.b("shopmanid","=", MainActivity.id);
            tfrList = db.selector(t_Feedback_Row.class)
                    .where("t_FB_M_ID","=",node.id)
                    .and(wb)
                    .findAll();
            if(tfrList!=null&&tfrList.size()>0) {
                boolean isShopMan = false;
                for (t_Feedback_Row tfr : tfrList) {
                    RMain.TablesBean.RowsBean.Q2Bean rRow = rQuery.getRowByRowId(tfr.getrrowid());
                    if (rRow == null)
                        continue;
                    FU_row rowNode = new FU_row();
                    Employee emp = db.selector(Employee.class).where("ID", "=", tfr.getshopmanid()).findFirst();
                    rowNode.rowName = rRow.getReportRowName();
                    rowNode.shopMan = emp != null ? emp.getFirstName() : "";
                    rowNode.ocDesc = tfr.getocDesc();
                    rowNode.rowStates = tfr.getstates();
                    rowNode.wentifenxi = tfr.getwentifenxi();
                    rowNode.xingdongjihua = tfr.getxingdongjihua();
                    rowNode.miaoshu = tfr.getmiaoshu();
                    rowNode.id = tfr.getId();
                    rowNode.trrid = tfr.gettrrid();
                    rowNode.shopmanid = tfr.getshopmanid();
                    rowNode.shopName = node.shopName;
                    rowNode.empId = node.empId;
                    rowNode.unULCount = tfr.getunULCount();
                    fuRowList.add(rowNode);
                    if (tfr.getstates() != 222)
                        shallWePass = false;
                    if(tfr.getunULCount() > 0)
                        isAllUL = false;
                    if (tfr.getshopmanid() == MainActivity.id)
                        isShopMan = true;
                    //Log.i("initDataList",tfr.toString());
                }
                if (isShopMan)
                    status++;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return fuRowList;
    }

    private void submitOrPass(){
        if (shallWePass) {
            //Log.i("FollowUpRowActivity", "onClick--> passWTZZ");
            submitData("passWTZZ");
        } else {
            //Log.i("FollowUpRowActivity", "onClick--> saveFeedbackData");
            submitData("saveFeedbackData");
        }
    }

    private void submitData(final String task){
        RequestParams params = new RequestParams(pubClass.Server_namehzm);
        //params.setSslSocketFactory(...); // 设置ssl
        params.addQueryStringParameter("task", task);
        params.addQueryStringParameter("schid", Integer.toString(node.schId));
        if(tfrList==null || tfrList.size()<1)
            return;
        if(!isAllUL){
            Toast.makeText(FollowUpRowActivity.this, "请先提交‘整改结果’橙色项中的附件", Toast.LENGTH_LONG).show();
            return;
        }
        if(task.equals("saveFeedbackData")){
            Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
            params.addQueryStringParameter("rowList", gson.toJson(tfrList));
        }
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
                String[] resArry = result.split("\\|");
                String succText = task.equals("saveFeedbackData")?"提交成功，自动跳转":"确认通过，自动跳转";
                String failText = task.equals("saveFeedbackData")?"提交失败，请稍后再试":"未能通过，请稍后再试";
                if (resArry[0].equals("200")){
                    try {
                        switch(task){
                            case "saveFeedbackData":
                                for(t_Feedback_Row tfr:tfrList){
                                    tfr.setstates(222);
                                    db.saveOrUpdate(tfr);
                                }
                                break;
                            case "passWTZZ":
                                for(t_Feedback_Row tfr:tfrList){
                                    tfr.setstates(333);
                                    db.saveOrUpdate(tfr);
                                }
                                t_Feedback_Main tfm = db.selector(t_Feedback_Main.class)
                                        .where("schid","=",node.schId)
                                        .findFirst();
                                if(tfm!=null){
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                                    String currentTime = sdf.format(new Date()).replace(' ', 'T');
                                    tfm.setstates(currentTime.compareTo(tfm.getexTime().substring(0,19))>0?2:1);
                                    db.saveOrUpdate(tfm);
                                    Schedule sch = db.selector(Schedule.class)
                                            .where("ID","=",node.schId)
                                            .findFirst();
                                    if(sch != null){
                                        sch.setStates(4);
                                        sch.setIsNeedShopReport(3);
                                        db.saveOrUpdate(sch);
                                    }
                                }
                            break;
                        }
                        Toast.makeText(FollowUpRowActivity.this, succText, Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(FollowUpRowActivity.this, FollowUpActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(FollowUpRowActivity.this, failText, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(FollowUpRowActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(FollowUpRowActivity.this, "链接请求已取消", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
